package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //判断手机号是否存在
        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            log.info("code={}",code);
            //需要将生成的验证码保存到Session，待会进行校验
            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }
        return  R.error("验证码发送失败");
    }

    /**
     * 移动用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());
        //获取前端发送的手机号和验证码(String)
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session里获取到手机号对应的正确的验证码
        Object codeInsession = session.getAttribute(phone);
        //进行验证码比对
        if(codeInsession !=null && codeInsession.equals(code)){
            //验证成功，登录
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User user = userService.getOne(qw);
            //判断是否为新用户
            if(user == null){
                //是新用户，自动完成注册、
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //此处有两个session，一个存的是验证码，
            //                    另一个是下面要存入的user数据
            session.setAttribute("user",user.getId());
            //清除验证码
            session.removeAttribute(phone);
            return R.success(user);
        }
        return R.error("登陆失败");
    }

    /**
     * 用户退出
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        //清空session中的数据，并跳转到登陆页面（前台写好后自动跳转）
       //session.invalidate();
        session.removeAttribute("user");//清楚登录的用户数据
        return R.success(null);
    }
}
